package it.valeandre.omino.image;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import android.graphics.Bitmap;

public class SimpleImageCache {
	public HashSet<String> mScheduledImages = new HashSet<String>();
	public ConcurrentHashMap<String, Bitmap> mBitmapCache = new ConcurrentHashMap<String, Bitmap>();
	public ConcurrentHashMap<String, HashSet<Integer>> mReservedBitmap = new ConcurrentHashMap<String, HashSet<Integer>>();
	public HashSet<String> mAlreadyRequestedURL = new HashSet<String>();

	public void unreserve(String url, int position) {
		if (mReservedBitmap.containsKey(url)) {
			HashSet<Integer> reservationCount = mReservedBitmap.get(url);

			reservationCount.remove(position);

			if (reservationCount.size() == 0) {
				mReservedBitmap.remove(url);
			}
		}
	}

	public boolean isReserved(String url) {
		return mReservedBitmap.containsKey(url);
	}

	public void reserve(String url, int position) {
		HashSet<Integer> reservationCount;

		if (mReservedBitmap.containsKey(url)) {
			reservationCount = mReservedBitmap.get(url);
		} else {
			reservationCount = new HashSet<Integer>();
			mReservedBitmap.put(url, reservationCount);
		}

		reservationCount.add(position);
	}

	public void unreserveAllForPosition(int position) {
		for (String url : getKeySetAsArray(mBitmapCache.keySet())) {
			if (url != null) {
				unreserve(url, position);
			}
		}
	}

	private ArrayList<String> getKeySetAsArray(Set<String> keySet) {

		ArrayList<String> list = new ArrayList<String>();

		try {
			for (String item: keySet) {
				if (item != null) {
					list.add(item);
				}
			}
		} catch (Exception e) {
		}
		/*
		 * String[] urls = new String[keySet.size()]; keySet.toArray(urls);
		 * 
		 * return urls;
		 */

		return list;
	}

	public void clearUnreservedBitmapCache() {
		int recycleCount = 0;

		for (String url : getKeySetAsArray(mBitmapCache.keySet())) {
			if (url != null && !isReserved(url)) {
				Bitmap bitmap = mBitmapCache.get(url);

				if (bitmap != null && !bitmap.isRecycled()) {
					bitmap.recycle();
					recycleCount++;
					mBitmapCache.remove(url);
				}
			}
		}

	}

	public void reset() {
		int recycleCount = 0;

		mReservedBitmap.clear();
		mScheduledImages.clear();
		mAlreadyRequestedURL.clear();

		for (Bitmap bitmap : mBitmapCache.values()) {

			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
				recycleCount++;
			}
		}

		mBitmapCache.clear();

	}

	public void put(String url, Bitmap bitmap) {
		mBitmapCache.put(url, bitmap);
	}

	public Bitmap get(String url) {
		if (mBitmapCache.containsKey(url)) {
			return mBitmapCache.get(url);
		}
		return null;
	}
}
